package net.xuele.learn.retry;

import com.github.rholder.retry.*;
import com.google.common.base.Predicates;

import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;


/**
 * @Author: yubo
 * @date: 17:49 2020/5/26
 * @Description: 类描述
 */

public class TestRetry {
    private final static Retryer<String> RETRYER = RetryerBuilder.<String>newBuilder()
            // 当重试的方法返回null时候进行重试
            .retryIfResult(Predicates.isNull())
            // 当重试方法抛出IOException类型异常时候进行重试
            .retryIfExceptionOfType(IOException.class)
            // 尝试执行三次（也就是重试2次）
            .withStopStrategy(StopStrategies.stopAfterAttempt(3))
            // 重试间隔
            .withWaitStrategy(WaitStrategies.fixedWait(2, TimeUnit.SECONDS))
            .withRetryListener(new MyRetryListener())
            .build();

    public static void main(String[] args) {
        Callable callable = new Callable() {
            private int count = 0;

            @Override
            public Object call() throws Exception {
                if (count != 2) {
                    count++;
                    return null;
                }
                return "ok";

            }
        };

        try {
            String result = RETRYER.call(callable);
            System.out.println(result);
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (RetryException e) {
            e.printStackTrace();
        }
    }

    static class MyRetryListener implements RetryListener {

        @Override
        public <V> void onRetry(Attempt<V> attempt) {
            System.out.println("retry...." + attempt.hasResult());
        }
    }
}
